<template>
  <div class="online-process-detail content bg-white full-height">
    <template>
      <div class="q-pa-md">
        <div class="row title-box">
          <div class="col-lg-3  col-sm-6 font-size-16">在产：<span class="font-size-14">{{data.productName}}<q-tooltip>{{data.productName}}</q-tooltip></span></div>
          <div class="col-lg-3  col-sm-6 font-size-16">工序：<span class="font-size-14">{{data.processPlanningName}}<q-tooltip>{{data.processPlanningName}}</q-tooltip></span></div>
          <div class="col-lg-3  col-sm-6 font-size-16">设备：<span class="font-size-14">{{data.deviceName}}<q-tooltip>{{data.deviceName}}</q-tooltip></span></div>
          <div class="col-lg-3  col-sm-6 font-size-16 equipment-name">
            所在位置：<span class="font-size-14">{{data.workshopName || '--'}}<q-tooltip>{{data.workshopName || '--'}}</q-tooltip></span>
          </div>
        </div>
      </div>
    </template>
    <template>
      <div class="q-pa-md">
        <q-table
          table-class="procedure-table"
          :data="programs"
          :columns="programColumns"
          row-key="name"
          no-data-label="暂无数据"
          :visible-columns="visibleColumns"
          hide-bottom
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="bor-t bor-b"
              >
                {{ col.label }}
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td key="programName" :props="props" class="bor-b" :class="{ on: props.row.isCurrentExecute}">
                {{ props.row.programName}}
              </q-td>
              <q-td key="programSize" :props="props" class="bor-b" :class="{ on: props.row.isCurrentExecute}">
                {{props.row.programSize}}K
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
    </template>
    <template>
      <div class="q-pa-md">
        <q-table
          table-class="row-table"
          :data="commandsData"
          :columns="rowColumns"
          row-key="name"
          no-data-label="暂无数据"
          hide-bottom
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="bor-t bor-b"
              >
                {{ col.name === 'commands' ? `${currentCommand}/${commandCount}`:col.label }}
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td key="row" :props="props" class="row-num bor-b ">
                {{ props.row.row}}
              </q-td>
              <q-td key="commands" :props="props" class="bor-b">
                {{ props.row.commands}}
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
    </template>
  </div>
</template>

<script>
import { getDetailed, isUnBind } from 'src/boot/program-v2/online'
import { sendUatMsg } from '../../boot/status-monitor/machine.js'
import refreshMixin from '../../assets/js/refresh-mixin'
import { mapGetters, mapMutations } from 'vuex'
import _ from 'lodash'
export default {
  name: 'online-process-detail',
  mixins: [refreshMixin],
  computed: {
    ...mapGetters([
      'userInfo',
      'client',
      'footprint'
    ])
  },
  data () {
    return {
      // pagination: {
      //   rowsPerPage: 0
      // },
      visibleColumns: ['programName', 'programSize'], // 工序表显示字段
      programColumns: [
        { name: 'programName', label: '程序名称', align: 'left', field: 'programName' },
        { name: 'programSize', label: '文件大小', align: 'left', field: 'programSize' },
        { name: 'isrowExecute', label: '', align: 'left', field: 'isrowExecute' }
      ], // 工序表头
      programs: [], // 工序表数据
      schemeLevelName: '', // 计划名
      rowColumns: [
        { name: 'row', label: '当前执行:', align: 'center', field: 'row' },
        { name: 'commands', label: '4/200', align: 'left', field: 'commands' }
      ], // 当前执行表头
      data: {},
      //  mqtt实例
      // 查询定时器
      timerGetDetail: null,
      reportType: 3, // 发送数据字段
      timerTime: null,
      commandCount: '', // 总行数
      currentCommand: '--', // 当前行数
      commandsData: [] // 当前执行表数据
    }
  },
  mounted () {
  },
  beforeDestroy () {
    // 取消订阅
    this.closeUbscribeTopic()
    if (this.timerTime) {
      clearInterval(this.timerTime)
    }
  },
  beforeRouteUpdate () {
    // 取消订阅
    this.closeUbscribeTopic()
  },
  watch: {
    '$route' (to, from) {
      if (to.name === 'online-process-detail') {
        this.init(to.query)
        this.commandsData = []
        this.currentCommand = '--'
      }
    }
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.init(this.$route.query)
    },
    init (query) {
      this.data = query
      this.getProcessingDetail()
      isUnBind(query.deviceId).then(res => {
        if (!res.data) {
          this.closeBox()
        } else {
          this.initMqtt()
        }
      })
    },
    /**
     * 初始化mqtt
     */
    initMqtt () {
      if (this.client) {
        this.onConnect()
        this.timerTime && clearInterval(this.timerTime)
        this.timerTime = setInterval(() => {
          sendUatMsg({
            cmd: 2,
            deviceId: this.data.deviceId,
            reportType: this.reportType,
            path: 1
          })
        }, 60000)
      } else {
        console.log('websocket未连接')
      }
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      // 区分是否是dnc
      const ret = JSON.parse(message.body)
      let msgBoxIds = message.headers.destination
      if (msgBoxIds.indexOf('DNC') > -1) {
        let msgArr = ret.data.split('|')
        const msg = {}
        // 奇数位为 key，偶数位为 value
        console.log(new Date(msgArr[0]))
        if (msgArr[0].includes('-') && msgArr[0].includes('T') && msgArr[0].includes('Z')) {
          msgArr = _.tail(msgArr)
        }
        for (let i = 0; i < msgArr.length; i += 2) {
          msg[msgArr[i]] = msgArr[i + 1]
        }
        if (!_.has(msg, 'line') && !_.has(msg, 'block')) return
        this.currentCommand = msg.line || '--'
        // 超过三行去掉一行
        this.commandsData = this.commandsData.length === 3 ? [ ..._.drop(this.commandsData), { row: msg.line, commands: msg.block } ]
          : [...this.commandsData, {
            row: msg.line,
            commands: msg.block
          }]
      } else {
        let msg = ret.data
        console.log(msg, '序列化的消息')
        // runType为1时，切换当前程序
        if (msg.runType) {
          this.getProcessingDetail()
          // this.commandCount = msg.count
          this.currentCommand = '--'
          this.commandsData = []
        }
      }
    },
    /**
     * 订阅并发送消息
     */
    onConnect () {
      console.log('加工详情订阅成功')
      this.client.subscribe(
        `${this.CommonConfig.socketConfig.SOCKET_TOPIC.programName.subscribeTopic}${this.data.deviceId}`,
        this.onMessageArrived,
        { id: `${this.CommonConfig.socketConfig.SOCKET_TOPIC.programName.subscribeTopic}${this.data.deviceId}` }
      )
      this.client.subscribe(
        `${this.CommonConfig.socketConfig.SOCKET_TOPIC.onlineProcessDetail.subscribeTopic}${this.data.deviceId}`,
        this.onMessageArrived,
        { id: `${this.CommonConfig.socketConfig.SOCKET_TOPIC.onlineProcessDetail.subscribeTopic}${this.data.deviceId}` }
      )
      // 订阅盒子绑定消息
      this.client.subscribe(
        `${this.CommonConfig.socketConfig.SOCKET_TOPIC.boxTypeTopic.subscribeTopic}${this.data.deviceId}`, this.getBoxType,
        { id: `${this.CommonConfig.socketConfig.SOCKET_TOPIC.boxTypeTopic.subscribeTopic}${this.data.deviceId}` }
      )
    },
    // 获取盒子相关信息
    getBoxType (res) {
      const member = JSON.parse(res.body).data
      if (member.isUnbound && member.deviceId === this.data.deviceId) {
        this.closeUbscribeTopic()
        this.timerTime && clearInterval(this.timerTime)
        if (!this.$route.fullPath.includes('online-process-detail')) return
        this.closeBox()
      }
    },
    closeBox () {
      this.timerTime && clearInterval(this.timerTime)
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>盒子已被解绑，请刷新界面</p>`,
        persistent: true,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        }
      }).onOk(() => {
        this.$router.push('/main/program-v2/online-process')
        const footprint = this.footprint.filter(v => !v.link.includes('online-process-detail'))
        this.set_footprint(footprint)
      })
    },
    /**
     * 取消订阅
     */
    closeUbscribeTopic () {
      console.log('断开加工详情订阅')
      this.client.unsubscribe(`${this.CommonConfig.socketConfig.SOCKET_TOPIC.onlineProcessDetail.subscribeTopic}${this.data.deviceId}`)
      this.client.unsubscribe(`${this.CommonConfig.socketConfig.SOCKET_TOPIC.programName.subscribeTopic}${this.data.deviceId}`)
      this.client.unsubscribe(`${this.CommonConfig.socketConfig.SOCKET_TOPIC.boxTypeTopic.subscribeTopic}${this.data.deviceId}`)
    },
    // 获取详情
    getProcessingDetail () {
      getDetailed(this.data.deviceId).then(res => {
        res.data.programs.forEach((item, index) => {
          item.index = index
        })
        this.programs = res.data.programs
        this.schemeLevelName = res.data.schemeLevelName
        this.commandCount = res.data.commandCount
        this.data.workshopName = res.data.workshopName
        this.data.productName = this.$utils.label(res.data.productNamesAndNumbers)
        const processPlanningName = this.$utils.label(res.data.processPlanningName)
        this.data.processPlanningName = _.isNil(res.data.processPlanningSort) || res.data.processPlanningSort === -1 ? processPlanningName : `${res.data.processPlanningSort + 1}-${processPlanningName}`
      })
    },
    ...mapMutations({
      'set_footprint': 'SET_FOOTPRINT'
    })
  },
  created () {
    this.init(this.$route.query)
  }
}
</script>

<style scoped lang="stylus">
  .font-size-16 {
    font-size 16px
  }
  .font-size-14 {
    font-size 14px
  }
  .title-box{
    padding 7px 30px
    border-top #D3D3D3 1px solid
    border-bottom #D3D3D3 1px solid
  }
  .equipment-name{
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }
  .max-h{
    max-height calc(40%);
  }
  td .item{
    margin-left 10px
  }
  td .item:first-child{
    margin-left 0
  }
  .row-table tr:last-child td{
    background-color rgba(95,119,253,.2)
  }
  .row-num{
    width 100px
    border-right #D3D3D3 1px solid
  }
  .bor-t{
    border-top #D3D3D3 1px solid
  }
  .bor-b{
    border-bottom #D3D3D3 1px solid
  }
  .bor-b.on{
    background-color rgba(95,119,253,.2)
  }
</style>
